package org.acghub.config.exchanger;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONWriter;
import lombok.extern.slf4j.Slf4j;
import org.acghub.config.*;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @Desc
 * @Author miyuki4j
 * @Date 2025/7/25/星期五 18:33
 * @Version 1.0
 */
@Slf4j
public class JsonTableDataExchanger implements TableDataExchanger {
    @Override
    public TableDataExchangerEnum type() {
        return TableDataExchangerEnum.JSON;
    }

    @Override
    public void exportData(String exportDir, TableData tableData) throws TableDataExportException {

        final TableMeta meta = tableData.getMeta();
        final String fileName = type().concatFileName(meta.getClassName());
        final File exportFile = new File(exportDir, fileName);
        if (exportFile.exists()) {
            exportFile.delete();
        }

        List<JSONWriter.Feature> features = new ArrayList<>();
        final boolean jsonPretty = TableConfig.get(TableConfig.ConfigKeyEnum.EXPORT_JSON_PRETTY, true);
        if (jsonPretty) {
            features.add(JSONWriter.Feature.PrettyFormat);
        }

        final JSONArray jsonArray = toJsonArray(tableData);

        try (FileOutputStream fos = new FileOutputStream(exportFile)) {
            JSON.writeTo(fos, jsonArray, features.toArray(new JSONWriter.Feature[0]));
        } catch (Exception e) {
            throw new TableDataExportException("导出文件失败, fileName：" + fileName, e);
        }
        log.debug("导出文件成功, fileName：{}", fileName);
    }

    private JSONArray toJsonArray(TableData tableData) {
        JSONArray jsonArray = new JSONArray();
        TableMeta tableMeta = tableData.getMeta();
        for (TableDataRow row : tableData) {
            JSONObject jsonObject = new JSONObject();
            for (TableDataCell cell : row) {
                Optional<TableField> tableFieldOptional = tableMeta.getHeader().get(cell.getColumn());
                if (tableFieldOptional.isEmpty()) {
                    continue;
                }
                jsonObject.put(tableFieldOptional.get().getName(), cell.getExportValue());
            }
            jsonArray.add(jsonObject);
        }
        return jsonArray;
    }

    /**
     * 从json文件中导入数据
     */
    @Override
    public ImportData importData(File file) throws TableDataImportException {
        try (FileInputStream fis = new FileInputStream(file)) {
            JSONArray jsonArray = JSON.parseArray(fis);
            String className = type().cutClassName(file.getName());
            return toImportData(className, jsonArray);
        } catch (Exception e) {
            throw new TableDataImportException("导入文件失败, fileName：" + file.getName(), e);
        }
    }

    private ImportData toImportData(String className, JSONArray jsonArray) {
        ImportData importData = new ImportData(className);
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            TableDataRow row = new TableDataRow(i + 1);
            for (String key : jsonObject.keySet()) {
                row.add(new TableDataCell(key, jsonObject.getString(key)));
            }
            importData.add(row);
        }
        return importData;
    }
}
